<template>
	<div>
		<el-dialog title="导入excel" width="600px" :visible.sync="show" @close="closeForm" append-to-body>
			<el-upload v-if="!process" class="upload-demo" action :auto-upload="false" :show-file-list="false" :on-change="choose_file">
				<el-button size="mini" icon="el-icon-upload" type="primary">请选择导入excel</el-button> <span style="color:#ff0000">{{file.name}}</span>
			</el-upload>
			<el-progress v-else :percentage="percentage"></el-progress>
			<div slot="footer" class="dialog-footer">
				<el-button :size="size" :loading="loading" type="primary" @click="submit" >
					<span v-if="!loading">确 定</span>
					<span v-else>提 交 中...</span>
				</el-button>
				<el-button :size="size" @click="closeForm">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
import { importFdData } from '@/api/app/saleoutstock'
	import XLSX from "xlsx"
	export default {
		name:'saleOutStockimportFdData',
		props: {
			show: {
				type: Boolean,
				default: true
			},
			size: {
				type: String,
				default: 'mini'
			},
		},
		data() {
			return {
				file: "",
				process:false,
				loading:false,
				excel_import_data:[],
				percentage:0,
				page:1,
				limit:0,
			}
		},
		methods: {
      choose_file(file) {
        this.file = file
        this.importExcel(file)
      },
      importExcel(file) {
        var excelData = []
        const fileReader = new FileReader()
        fileReader.onload = (ev) => {
          try{
            const data = ev.target.result
            const workbook = XLSX.read(data, { type: "binary" })

            // 关键修改：获取第一个sheet页（无论名称）
            const firstSheetName = workbook.SheetNames[0];
            excelData.push(
                ...XLSX.utils.sheet_to_json(workbook.Sheets[firstSheetName])
            )

            this.excel_import_data = excelData
          }catch(e){
            this.$message.danger('文件类型不正确')
          }
        }
        fileReader.readAsBinaryString(file.raw)
      },
			submit(){
        this.process = true
        this.loading = true
        // 使用固定分页大小，避免每次重置为总长度
        const pageSize = 500; // 设置固定分页大小
        const total_page = Math.ceil(this.excel_import_data.length / pageSize)

        // 正确计算当前进度
        this.percentage = Math.ceil((this.page / total_page) * 100)

        importFdData(this.getData(pageSize)).then(res => {
          if(res.status == 200){
            // 修改递归条件判断逻辑
            if(this.page < total_page){
              this.page = this.page + 1
              this.submit()
            } else {
              console.log(res)
              this.$message({
                message: '导入完成,成功数量:' + res.data.successCount + ",失败数量:" + res.data.failCount,
                showClose:true,
                duration:0,
                type: 'success'})
              this.$emit('refresh_list')
              this.closeForm()
            }
          }
        }).catch(() => {
          this.loading = false
        })
			},
      getData(pageSize) {
        const start = (this.page - 1) * pageSize;
        const end = start + pageSize;
        return this.excel_import_data.slice(start, end);
      },
			closeForm(){
				this.$emit('update:show', false)
				this.file = ''
				this.process = false
				this.percentage = 0
				this.loading = false
				this.page = 1
				this.limit = 0
			}
		}
	}
</script>
